package com.yq.cp.config.kl;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.yq.cp.config.LogPrintAspect;
import com.yq.cp.entity.data.NengKongData;
import com.yq.cp.mapper.data.NengKongDataMapper;
import com.yq.cp.utils.Authorization;
import com.yq.cp.utils.DateTimeUtil;
import com.yq.cp.utils.RedisUtil;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.logging.log4j.LogManager;
import org.apache.xmlbeans.impl.xb.xsdschema.Public;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

@Component
public class DyUtil {

    private static String code="saRipg";
    private static String ym="https://gateway.isolarcloud.com";
    private static String appkey="DA4079B6D276A6786D98A448DE10B826";
    private static String token="mg2hedcrw2vabkpkhxhtcs4w78cmfthf";
    private static String access_token="0e09d67b-1c3a-466e-8731-fea494579eaf";
    private static String refresh_token="f9ebb620-e2f7-41c3-9f83-c514dbb51997";

    private static final Logger logger = LoggerFactory.getLogger(Authorization.class);
    @Resource
    RedisUtil redisUtil;
    @Resource
    Authorization authorization;
    @Resource
    NengKongDataMapper nengKongDataMapper;

    public static void main(String[] args) {
        DyUtil dyUtil=new DyUtil();
        dyUtil.cxzd();
    }
    public void cxnbq(String device_sn,Integer state,Integer i){
        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = ym+"/openapi/platform/getDeviceRealTimeData";
        HttpPost httppost = new HttpPost(url);
        try
        {
            // 设置头
            httppost.addHeader("x-access-key", token);
            httppost.addHeader("Authorization",  "Bearer "+access_token);
            HashMap<String, Object> req = new HashMap<String, Object>();
            // 公共参数
            req.put("appkey", appkey);
            req.put("token", token);
            // 业务相关
//            {
//                "device_type":"14",
//                    "is_get_point_dict":"1",
//                    "point_id_list": ["83022","13134","13112","13176"],
//                "ps_key_list": ["700666130_22_247_3","700666130_22_247_2","700666130_14_1_2"]
//            }
            req.put("service", "查询设备数据");
            req.put("device_type", "1");
            req.put("is_get_point_dict", "1");
            List<String> list1=new ArrayList<>();
            list1.add("2");
            list1.add("14");
            list1.add("24");
            req.put("point_id_list", list1);
            List<String> list2=new ArrayList<>();
            list2.add(device_sn);
            req.put("sn_list",list2);
            List<Integer> types=new ArrayList<>();
            types.add(1);
            req.put("device_type_list", types);
            String jsonStr = com.alibaba.fastjson.JSON.toJSONString(req);
            logger.info("send json-<" + jsonStr.toString());
            StringEntity strEntity = new StringEntity(jsonStr);
            strEntity.setContentType("application/json");
            httppost.setEntity(strEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String s;
                logger.info(reader.toString());
                while (((s = reader.readLine()) != null))
                {
                    result.append(s);
                }
                reader.close();
                logger.info("receive json-<" + result.toString());
                String fhz=result.toString();

                /*
                    {
                        "req_serial_num": "202411221b7e46c98105cb2465eaef6c",
                        "result_code": "1",
                        "result_msg": "success",
                        "result_data": {
                            "point_dict": [
                                {
                                    "point_id": 2,
                                    "point_unit": "Wh",
                                    "point_name": "总发电量"
                                }
                            ],
                            "device_point_list": [
                                {
                                    "device_point": {
                                        "device_name": "NB01",
                                        "dev_fault_status": 4,
                                        "p2": "11300.0",
                                        "ps_key": "1801915_1_1_1",
                                        "device_sn": "A24A2900627",
                                        "dev_status": 0,
                                        "ps_id": 1801915,
                                        "communication_dev_sn": "A24A2114743",
                                        "uuid": 13948146,
                                        "device_time": "20241120111000"
                                    }
                                }
                            ]
                        }
                    }
                * */
                JSONObject jsonObject = JSONObject.parseObject(fhz);
                JSONObject jsonObject1 = jsonObject.getJSONObject("result_data").getJSONArray("device_point_list").getJSONObject(0);
                BigDecimal p2 = jsonObject1.getJSONObject("device_point").getBigDecimal("p2");
                BigDecimal p14 = jsonObject1.getJSONObject("device_point").getBigDecimal("p14");
                BigDecimal p24 = jsonObject1.getJSONObject("device_point").getBigDecimal("p24");
                //设备当前故障状态设备故障状态：1：故障，2：告警，4：正常
                if (state==4){
                    state=1;
                }else {
                    state=2;
                }
                if (p14==null){
                    p14=new BigDecimal(0);
                }
                if (p2==null){
                    p2=new BigDecimal(0);
                }
                p14=p14.divide(new BigDecimal(1000));
                p2=p2.divide(new BigDecimal(1000));
                logger.info("查询阳光云逆变器-sn：" + device_sn);
                logger.info("查询阳光云逆变器-发电量：" + p2);
                logger.info("查询阳光云逆变器-功率：" + p14);
                authorization.xrsj(device_sn,state,p14,p2,i);

            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    public void cxsb(String ps_id){
//        access_token = redisUtil.get("access_token").toString();
//        refresh_token = redisUtil.get("refresh_token").toString();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = ym+"/openapi/platform/getDeviceListByPsId";
        HttpPost httppost = new HttpPost(url);
        try
        {
            // 设置头
            httppost.addHeader("x-access-key", token);
            httppost.addHeader("Authorization",  "Bearer "+access_token);
            HashMap<String, Object> req = new HashMap<String, Object>();
            // 公共参数
            req.put("appkey", appkey);
            req.put("token", token);
            // 业务相关
            req.put("service", "查询设备列表");
            req.put("ps_id", ps_id);
            req.put("is_virtual_unit", "");
            req.put("claim_state", "");
            req.put("is_get_firmware_version", "1");
            req.put("page", 1);
            req.put("size", 10);
            List<Integer> types=new ArrayList<>();
            types.add(1);
            req.put("device_type_list", types);
            String jsonStr = com.alibaba.fastjson.JSON.toJSONString(req);
            logger.info("send json-<" + jsonStr.toString());
            StringEntity strEntity = new StringEntity(jsonStr);
            strEntity.setContentType("application/json");
            httppost.setEntity(strEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String s;
                logger.info(reader.toString());
                while (((s = reader.readLine()) != null))
                {
                    result.append(s);
                }
                reader.close();
                logger.info("receive json 设备-<" + result.toString());
                String fhz=result.toString();
                JSONObject jsonObject = JSONObject.parseObject(fhz);
                JSONArray jsonArray = jsonObject.getJSONObject("result_data").getJSONArray("pageList");
                for (int i = 0; i < jsonArray.size(); i++) {
                    String device_sn = jsonArray.getJSONObject(i).getString("device_sn");
                    //设备当前在线离线状态：0：离线，1：在线
                    Integer dev_status = jsonArray.getJSONObject(i).getInteger("dev_status");
                    //设备当前故障状态设备故障状态：1：故障，2：告警，4：正常
                    Integer dev_fault_status = jsonArray.getJSONObject(i).getInteger("dev_status");
                    Integer state=1;
                    if (dev_status==1){
                        if (dev_fault_status==4){
                            state=1;
                        }else {
                            state=3;
                        }
                    }else {
                        state=2;
                    }
                    cxnbq(device_sn,state,i);
                }
            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    public void cxnyzxq(String ps_id){
//        access_token = redisUtil.get("access_token").toString();
//        refresh_token = redisUtil.get("refresh_token").toString();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = ym+"/openapi/platform/getPowerStationRealTimeData";
        HttpPost httppost = new HttpPost(url);
        try
        {
            // 设置头
            httppost.addHeader("x-access-key", token);
            httppost.addHeader("Authorization",  "Bearer "+access_token);
            HashMap<String, Object> req = new HashMap<String, Object>();
            // 公共参数
            req.put("appkey", appkey);
            req.put("token", token);
            // 业务相关
            req.put("service", "查询能源站实时观测数据");
            List<String> list=new ArrayList<>();
            list.add(ps_id);
            req.put("ps_id_list", list);
            List<Integer> pointS=new ArrayList<>();
            pointS.add(83025);
            req.put("point_id_list", pointS);
            String jsonStr = com.alibaba.fastjson.JSON.toJSONString(req);
            logger.info("send json-<" + jsonStr.toString());
            StringEntity strEntity = new StringEntity(jsonStr);
            strEntity.setContentType("application/json");
            httppost.setEntity(strEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String s;
                logger.info(reader.toString());
                while (((s = reader.readLine()) != null))
                {
                    result.append(s);
                }
                reader.close();
                logger.info("receive json 电站实时观测数据-<" + result.toString());
                String fhz=result.toString();
                JSONObject jsonObject = JSONObject.parseObject(fhz);
                JSONArray jsonArray = jsonObject.getJSONObject("result_data").getJSONArray("device_point_list");
                for (int i = 0; i < jsonArray.size(); i++) {
                    JSONObject jsonObject1 = jsonArray.getJSONObject(i);
                    BigDecimal fullHour = jsonObject1.getBigDecimal("p83025");
                    logger.info("receive json 电站详细数据-等效小时数-<" + fullHour);

                    NengKongData glData=new NengKongData();
                    glData.setName("等效小时数");
                    glData.setValue(fullHour);
                    glData.setProduceTime(DateTimeUtil.dqsj());
                    glData.setEnergyCode(ps_id);
                    glData.setMacCode(null);
                    glData.setHourTime(DateTimeUtil.dqsj());
                    nengKongDataMapper.insert(glData);
                }
            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
    public void cxzd(){
        access_token = redisUtil.get("access_token").toString();
        refresh_token = redisUtil.get("refresh_token").toString();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = ym+"/openapi/platform/queryPowerStationList";
        HttpPost httppost = new HttpPost(url);
        try
        {
            // 设置头
            httppost.addHeader("x-access-key", token);
            httppost.addHeader("Authorization",  "Bearer "+access_token);
            HashMap<String, Object> req = new HashMap<String, Object>();
            // 公共参数
            req.put("appkey", appkey);
            req.put("token", token);
            // 业务相关
//            {
//                "ps_type":"1,3,4,5,6,7,8",
//                    "ps_name":"",
//                    "page": 1,
//                    "size": 10,
//                    "valid_flag":"1,3"
//            }
            req.put("service", "查询电站列表");
            req.put("ps_type", "1,3,4,5,6,7,8");
            req.put("ps_name", "");
            req.put("page", 1);
            req.put("size", 10);
            req.put("valid_flag", "1,3");
            String jsonStr = com.alibaba.fastjson.JSON.toJSONString(req);
            logger.info("send json-<" + jsonStr.toString());
            StringEntity strEntity = new StringEntity(jsonStr);
            strEntity.setContentType("application/json");
            httppost.setEntity(strEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String s;
                logger.info(reader.toString());
                while (((s = reader.readLine()) != null))
                {
                    result.append(s);
                }
                reader.close();
                logger.info("receive json 能源站-<" + result.toString());
                String fhz=result.toString();
                JSONObject jsonObject = JSONObject.parseObject(fhz);
                JSONArray jsonArray = jsonObject.getJSONObject("result_data").getJSONArray("pageList");
                for (int i = 0; i < jsonArray.size(); i++) {
                    String ps_id = jsonArray.getJSONObject(i).getString("ps_id");
                    cxsb(ps_id);
                    cxnyzxq(ps_id);
                }
            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }


    public void sxlp(){
        access_token = redisUtil.get("access_token").toString();
        refresh_token = redisUtil.get("refresh_token").toString();

        CloseableHttpClient httpclient = HttpClients.createDefault();
        String url = ym+"/openapi/apiManage/refreshToken";
        HttpPost httppost = new HttpPost(url);
        try
        {
            // 设置头
            httppost.addHeader("x-access-key", token);
            HashMap<String, Object> req = new HashMap<String, Object>();
            // 公共参数
            req.put("appkey", appkey);
            req.put("token", token);
            // 业务相关
            req.put("service", "刷新令牌");
            req.put("refresh_token", refresh_token);
            String jsonStr = com.alibaba.fastjson.JSON.toJSONString(req);
            logger.info("send json-<" + jsonStr.toString());
            StringEntity strEntity = new StringEntity(jsonStr);
            strEntity.setContentType("application/json");
            httppost.setEntity(strEntity);
            CloseableHttpResponse response = httpclient.execute(httppost);
            try
            {
                HttpEntity entity = response.getEntity();
                InputStream inputStream = entity.getContent();
                InputStreamReader inputStreamReader = new InputStreamReader(
                        inputStream, "UTF-8");
                BufferedReader reader = new BufferedReader(inputStreamReader);
                StringBuilder result = new StringBuilder();
                String s;
                logger.info(reader.toString());
                while (((s = reader.readLine()) != null))
                {
                    result.append(s);
                }
                reader.close();
                logger.info("receive json-<" + result.toString());
                String fhz=result.toString();
                JSONObject jsonObject = JSONObject.parseObject(fhz);
                String accessToken=jsonObject.getJSONObject("result_data").getString("access_token");
                String refreshToken=jsonObject.getJSONObject("result_data").getString("refresh_token");

                redisUtil.set("access_token",accessToken);
                redisUtil.set("refresh_token",refreshToken);
//                {
//                        "req_serial_num": "20241122af79467c99f420170f9ec121",
//                        "result_code": "1",
//                        "result_msg": "success",
//                        "result_data": {
//                               "access_token": "f48b0b37-93f1-46b0-8a94-8143949c32b5",
//                                "refresh_token": "924954b9-f0cb-461e-8f94-98430443283c",
//                                "code": "1",
//                                "token_type": "bearer",
//                                "expires_in": 172799
//                    }
//                }
            }
            finally
            {
                response.close();
            }
        }
        catch (Exception e)
        {
            e.printStackTrace();
        }
        finally
        {
            try
            {
                httpclient.close();
            }
            catch (IOException e)
            {
                e.printStackTrace();
            }
        }
    }
}


